package views;

import DTO.ConstantesDTO;
import DTO.UsuarioDTO;
import Servicios.ServiciosFactory;
import views.panels.PanelIngreso;

import java.awt.BorderLayout;
import javax.swing.JOptionPane;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import controllers.LoginControl;
import Main.Main;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JPanel;

/**
 * Clase en la que se gestiona el ingreso a la aplicacion.
 * @author eagle_eye
 */
public class InterfazIngreso extends javax.swing.JFrame {

    private ImageIcon icono;
    private LoginControl loginControl = new LoginControl();
    Main main;

    /**
     * Se define una subclase dentro de la clase principal que hereda de keyAdapter
     *y que al detectar que se presionó la tecla Enter haga lo mismo que hace el
     *botón Aceptar cuando se hace click en el mismo
     */
    public class PresionarTecla extends KeyAdapter {

        @Override
        public void keyPressed(KeyEvent ke) {
            if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
                BAceptarActionPerformed(null);
            } else if (ke.getKeyCode() == KeyEvent.VK_ESCAPE) {
                BCancelarActionPerformed(null);
            }

        }
    }

    /**
     * Metodo que obtieene el user y passwd del usuario.
     * @return  {@link UsuaarioDTO}
     */
    public UsuarioDTO readUser() {
        String user = tfUser.getText();
        char[] passArray = pfContrasena.getPassword();
        String pass = new String(passArray);
        return new UsuarioDTO(user, pass);
    }

    /**
     * Constructor de la clase
     * @param main @link Main
     */
    public InterfazIngreso(Main app) {
        this.main = app;
        initComponents();
        icono = new ImageIcon(getClass().getResource("/views/images/icon.gif"));
        this.setIconImage(icono.getImage());

        BAceptar.addKeyListener(new PresionarTecla());
        pfContrasena.addKeyListener(new PresionarTecla());
        tfUser.addKeyListener(new PresionarTecla());
        PanelIngreso panel = new PanelIngreso();
        this.add(panel, BorderLayout.CENTER);
        this.panelLoading.setVisible(false);
        this.pack();
    }

    /**
     * Metodo que controla el nivel de acceso de los Usuarios del sistema.
     */
    public void doLogin() {

        InterfazPrincipal principal = new InterfazPrincipal();
//        UsuarioBO usuarioBO = new UsuarioBO();
      //  Usuario sesion = usuarioBO.encontrarUsuario(ServiciosFactory.getLoginServicio().getUsuarioDTO().getUsuario());
      //  InterfazPrincipal.setSesion(sesion);
        if (ServiciosFactory.getLoginServicio().getUsuarioDTO().getTipousuario() == 2) {
            principal.getjTabbedPane1().remove(7);
            principal.getjTabbedPane1().remove(5);
            principal.getjTabbedPane1().remove(4);

            JPanel panel = (JPanel) (principal.getjTabbedPane1().getComponentAt(0));
            ((JPanel)(panel.getComponent(0))).remove(1);
            ((JPanel)(panel.getComponent(0))).remove(0);
            ((JPanel)(panel.getComponent(1))).remove(2);
            ((JPanel)(panel.getComponent(1))).remove(1);

            panel = (JPanel) (principal.getjTabbedPane1().getComponentAt(1));
            panel.remove(3);
            panel.remove(2);
            panel.remove(1);

            panel = (JPanel) (principal.getjTabbedPane1().getComponentAt(2));
            panel.remove(0);

            panel = (JPanel) (principal.getjTabbedPane1().getComponentAt(3));
            panel.remove(5);
            panel.remove(4);
            panel.remove(2);
            panel.remove(1);

            this.setVisible(false);
            this.dispose();
            principal.setVisible(true);
            JOptionPane.showMessageDialog(principal, "Bienvenido "
                    + ServiciosFactory.getLoginServicio().getUsuarioDTO().getUsuario()
                    + "\nRol: Profesor.");

        } else if (ServiciosFactory.getLoginServicio().getUsuarioDTO().getTipousuario() == 3) {
            principal.getjTabbedPane1().remove(2);
            principal.getjTabbedPane1().remove(3);
            principal.getjTabbedPane1().remove(4);
            principal.getjTabbedPane1().remove(5);
            principal.getjTabbedPane1().remove(6);
            principal.getjTabbedPane1().remove(7);
            this.setVisible(false);
            this.dispose();
            principal.setVisible(true);
            JOptionPane.showMessageDialog(principal, "Bienvenido "
                    + ServiciosFactory.getLoginServicio().getUsuarioDTO().getUsuario()
                    + "\nRol: Estudiante.");

        } else {
            this.setVisible(false);
            this.dispose();
            principal.setVisible(true);
            JOptionPane.showMessageDialog(principal, "Bienvenido "
                    + ServiciosFactory.getLoginServicio().getUsuarioDTO().getUsuario()
                    + "\nRol: Administrador.");
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        tfUser = new javax.swing.JTextField();
        pfContrasena = new javax.swing.JPasswordField();
        BAceptar = new javax.swing.JButton();
        BCancelar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        panelLoading = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Sistema de Informacion Academica");
        setName("xD"); // NOI18N
        setResizable(false);
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                formKeyReleased(evt);
            }
        });

        jLabel1.setText("Usuario");

        jLabel2.setText("Contraseña");

        tfUser.setText("Prof40");

        pfContrasena.setText("Prof40");

        BAceptar.setFont(new java.awt.Font("Tahoma", 1, 11));
        BAceptar.setText("Aceptar");
        BAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BAceptarActionPerformed(evt);
            }
        });
        BAceptar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                BAceptarKeyReleased(evt);
            }
        });

        BCancelar.setFont(new java.awt.Font("Tahoma", 1, 11));
        BCancelar.setText("Cancelar");
        BCancelar.setRequestFocusEnabled(false);
        BCancelar.setRolloverEnabled(false);
        BCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BCancelarActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel3.setForeground(new java.awt.Color(0, 0, 255));
        jLabel3.setText("SISTEMA DE CONTROL ACADEMICO");

        panelLoading.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel4.setText("Espere por favor....");
        panelLoading.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 40, -1, -1));

        jLabel5.setIcon(new javax.swing.ImageIcon("resources/loading.gif"));
        panelLoading.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(114, 0, 240, 30));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(panelLoading, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(168, 168, 168)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel1))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(tfUser, javax.swing.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE)
                                    .addComponent(pfContrasena, javax.swing.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(BAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 48, Short.MAX_VALUE)
                                        .addComponent(BCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)))))))
                .addGap(35, 35, 35))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jLabel3)
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tfUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(pfContrasena, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BAceptar)
                    .addComponent(BCancelar))
                .addGap(18, 18, 18)
                .addComponent(panelLoading, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(58, 58, 58))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BAceptarActionPerformed
        UsuarioDTO usuario = readUser();
        try {
            int validate = ConstantesDTO.VALIDATE_DEFAULT;
            validate = loginControl.validate(usuario);
            switch (validate) {
                case ConstantesDTO.FORMATO_NOMBRE_INCORRECTO: {
                    JOptionPane.showMessageDialog(this, "El formato del nombre es incorrecto");
                    pfContrasena.setText("");
                    tfUser.setText("");
                    panelLoading.setVisible(false);
                    break;
                }
                case ConstantesDTO.FORMATO_CONTRASENA_INCORRECTO: {
                    JOptionPane.showMessageDialog(this, "El formato de la contraseña es incorrecto.\nLongitud entre 5 y 30 caracteres, inclusive."
                            + "\nDebe contener por lo menos:\n* Un número, una letra minúscula, una letra mayúscula.\nEj: Mysecret1.");
                    pfContrasena.setText("");
                    tfUser.setText("");
                    panelLoading.setVisible(false);
                    break;
                }
                case ConstantesDTO.LONGITUD_NOMBRE_INCORRECTO: {
                    JOptionPane.showMessageDialog(this, "La longitud del nombre es incorrecto");
                    break;
                }
                case ConstantesDTO.LONGITUD_CONTRASENA_INCORRECTO: {
                    JOptionPane.showMessageDialog(this, "La longitud de la contraseña es incorreta");
                    pfContrasena.setText("");
                    panelLoading.setVisible(false);
                    break;
                }
                case ConstantesDTO.LOGIN_EXITOSO: {

                    if (!usuario.getPassword().equals(ServiciosFactory.getLoginServicio().getUsuarioDTO().getPassword())) {
                        JOptionPane.showMessageDialog(this, "Password o Usuario errados");
                        pfContrasena.setText("");
                        tfUser.setText("");
                    } else {
                        doLogin();
                    }
                    break;
                }
                case ConstantesDTO.USUARIO_INEXISTENTE: {
                    JDialog.setDefaultLookAndFeelDecorated(true);
                    JOptionPane.showMessageDialog(this, "User y pass bien, pero usuario no existe");
                    panelLoading.setVisible(false);
                    break;
                }
            }
        } catch (Exception exception) {
            JOptionPane.showMessageDialog(null, "Error de conexion.");
            System.out.println("Error de conexion: " + exception.getMessage());
        }

    }//GEN-LAST:event_BAceptarActionPerformed

    private void BCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BCancelarActionPerformed
        System.exit(0);
    }//GEN-LAST:event_BCancelarActionPerformed

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_formKeyPressed

    private void formKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyReleased
        System.out.println("ohio");
    }//GEN-LAST:event_formKeyReleased

    private void BAceptarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_BAceptarKeyReleased
        System.out.println("ohio1");
    }//GEN-LAST:event_BAceptarKeyReleased

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BAceptar;
    private javax.swing.JButton BCancelar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel panelLoading;
    private javax.swing.JPasswordField pfContrasena;
    private javax.swing.JTextField tfUser;
    // End of variables declaration//GEN-END:variables
}
